package com.hmall.common.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.hmall.common.constants.MQConstants.ERROR_EXCHANGE_NAME;

@Configuration
@ConditionalOnProperty(name = "spring.rabbitmq.listener.simple.retry.enabled", havingValue = "true")
public class MqConsumeErrorAutoConfiguration {

    @Value("${spring.application.name}")    //从yaml文件中读取微服务名称
    private String applicationName;

    /**
     * 声明死心交换机
     *
     * @return
     */
    @Bean
    public DirectExchange errorExchange() {
        return new DirectExchange(ERROR_EXCHANGE_NAME);
    }

    /**
     * 声明死信队列
     *
     * @return
     */
    @Bean
    public Queue errorQueue() {
        return new Queue(applicationName + "error.queue");
    }

    /**
     * 绑定死信队列
     *
     * @param errorExchange
     * @param errorQueue
     * @return
     */
    @Bean
    public Binding errorQueueBinding(DirectExchange errorExchange, Queue errorQueue) {
        return BindingBuilder.bind(errorQueue).to(errorExchange).with(applicationName);
    }

    /**
     * 设置失败处理策略
     *
     * @param rabbitTemplate
     * @return
     */
    @Bean
    public MessageRecoverer messageRecoverer(RabbitTemplate rabbitTemplate) {
        return new RepublishMessageRecoverer(rabbitTemplate, ERROR_EXCHANGE_NAME, applicationName);
    }
}
